<template>
  <a-form layout="horizontal" :model="form" :rules="rules">
    <a-form-item field="userAccount" validate-trigger="blur" hide-label>
      <a-input
        v-model="form.userAccount"
        style="height: 40px"
        autocomplete="username"
        placeholder="请输入用户名"
      >
        <template #prefix>
          <icon-user />
        </template>
      </a-input>
    </a-form-item>
    <a-form-item field="userPassword" validate-trigger="blur" hide-label>
      <a-input-password
        v-model="form.userPassword"
        style="height: 40px"
        autocomplete="current-password"
        placeholder="请输入密码"
        allow-clear
      >
        <template #prefix>
          <icon-lock />
        </template>
      </a-input-password>
    </a-form-item>
    <a-form-item field="checkPassword" validate-trigger="blur" hide-label>
      <a-input-password
        v-model="form.checkPassword"
        style="height: 40px"
        autocomplete="current-password"
        placeholder="请确认密码"
        allow-clear
      >
        <template #prefix>
          <icon-lock />
        </template>
      </a-input-password>
    </a-form-item>
    <a-button type="primary" style="margin: 0 0 6px" long :loading="loading" @click="handleSubmit">
      注册
    </a-button>
  </a-form>
</template>
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { userRegisterUsingPost } from '@/api/userController.ts'
import { Message } from '@arco-design/web-vue'

const loading = ref(false)

const router = useRouter()

const form = reactive({
  userAccount: '',
  userPassword: '',
  checkPassword: '',
} as API.UserRegisterRequest)

const rules = {
  username: [{ required: true, message: '请输入账号' }],
  password: [
    { required: true, message: '请输入密码' },
    {
      // 密码格式：6-32位，包含大小写字母、数字、特殊字符(除空格)两种以上
      match: /^(?![\d]+$)(?![a-z]+$)(?![A-Z]+$)(?![~!@#$%^&*.]+$)[\da-zA-z~!@#$%^&*.]{6,32}$/,
      message: '密码格式不正确',
    },
  ],
  checkPassword: [
    { required: true, message: '请确认密码' },
    {
      validator: (value: string, cb: any) => {
        if (value !== form.userPassword) {
          cb('两次输入的密码不一致')
        } else {
          cb()
        }
      },
    },
  ],
  mobile: [{ required: true, message: '请输入手机号' }],
}

const handleSubmit = async () => {
  if (loading.value) return
  const res = await userRegisterUsingPost(form)
  if (res.data.code === 0) {
    Message.success('注册成功')
    router.push({
      path: '/user/login',
      replace: true,
    })
  } else {
    Message.error('注册失败，' + res.data.message)
  }
}
</script>

<style scoped>
.register-form-more {
  justify-content: center;
}

.register-form-more .arco-icon {
  font-size: 20px;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.register-form-more .arco-icon:hover {
  transform: scale(1.3);
}
</style>
